package com.googlecode.cryptoid;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.util.Stack;

import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class MessageList extends ListActivity {

	static final int ITEM_MENU_KEY = 0;
	
	public void onResume() {
		  super.onResume();
		  
		  final Intent intent = new Intent(this, MatrixList.class);
		  final String[] messages = getMessageList();
		  setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, messages));

		  ListView lv = getListView();
		  lv.setTextFilterEnabled(true);

		  lv.setOnItemClickListener(new OnItemClickListener() {
		    public void onItemClick(AdapterView<?> parent, View view,
		        int position, long id) {
		    	if(position == 0){
			    	  ViewMessage.newMessage = true;
			    	  startActivity(intent);
			    	  finish();
			      }
			      else {
			    	  ViewMessage.raw = messages[position];
			    	  startActivity(intent);
			    	  finish();
			      }
		    }
		  });
		  		  
		}
	
	private String[] getMessageList() {
		boolean inputReady = true;
		int len = 0;
		Stack<String> messagesStack = new Stack<String>();
		String[] initialList = {getString(R.string.new_)};
	
		
			ObjectInputStream input;
			try {
				input = new ObjectInputStream(openFileInput(".msglist"));
				if(inputReady){
					String[] messagesIn = (String[]) input.readObject();
					input.close();
				
					len = messagesIn.length;
					
					for(int i = 1; i <= len; i++)
						messagesStack.add(messagesIn[len - i]);
					
				}
			}
			  catch (FileNotFoundException e) {
				return initialList;
			} catch (StreamCorruptedException e) {
				return initialList;
			} catch (IOException e) {
				return initialList;
			} catch (ClassNotFoundException e) {
				return initialList;
			} 
		
			String[] messages = new String[len+1];
			
			messages[0] = "New...";
			for(int i = 1; i < len+1; i ++)
				messages[i] = messagesStack.pop();
			
			return messages;
	}
	
}
